package hydrap2p.hubmanager;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

import hydrap2p.ServiceLocation;
import hydrap2p.hub.HubListener;
import hydrap2p.hub.HubStatus;

public class ThriftListener implements Listener {

	private ServiceLocation location;
	private HubListener.Iface listener;
	
	public ThriftListener(ServiceLocation listenerloc)
	{
		this.location=listenerloc;
	}
	
	public void connect() throws TException
	{
		TTransport transport = new TSocket(location.address,location.port);
		transport.open();
		listener=new HubListener.Client(new TBinaryProtocol(transport));
		if (!listener.supportedInterfaces().contains("ModuleListener"))
			throw new TException("Invalid Listener, missing ModuleListener");
	}

	@Override
	public void connectionAdded(HubStatus status) throws Exception {
		listener.connectionAdded(status);
	}

	@Override
	public void connectionChanged(HubStatus status) throws Exception {
		listener.connectionChanged(status);
	}

	@Override
	public void connectionRemoved(HubStatus status) throws Exception {
		listener.connectionRemoved(status);
	}

	@Override
	public void connectionConnected(HubStatus status) throws Exception {
		listener.connectionConnected(status);
	}

	@Override
	public void protocolRegistered(String name) throws Exception {
		listener.protocolRegistered(name);
	}

	@Override
	public void protocolUnregistered(String name) throws Exception {
		listener.protocolUnregistered(name);
	}

	@Override
	public void stop() {
		// Do nothing
	}

	public ServiceLocation getLocation()
	{
		return location;
	}

	@Override
	public int hashCode()
	{
		return location.hashCode();
	}
	
	@Override
	public boolean equals(Object obj)
	{
		if (obj instanceof ThriftListener)
		{
			ThriftListener other = (ThriftListener) obj;
			return other.location.equals(this.location);
		}
		return false;
	}
	
	@Override
	public String toString()
	{
		return "HubListener at "+location;
	}
}
